#!/bin/bash

# 设置颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 默认参数
INTERVAL=5      # 采样间隔（秒）
DURATION=60     # 监控时长（秒）
OUTPUT_FILE="network_performance_report_$(date +%Y%m%d_%H%M%S).txt"
INTERFACE=""     # 网卡接口名称
COLLECT_IFTOP=true  # 默认启用iftop
COLLECT_TCP=true   # 默认启用TCP监控

# 帮助信息
show_help() {
    echo "用法: $0 [选项]"
    echo "选项:"
    echo "  -i, --interval <秒>   采样间隔（默认: 5秒）"
    echo "  -d, --duration <秒>   监控时长（默认: 60秒）"
    echo "  -e, --interface <名称> 指定网卡名称（默认: 自动检测默认网卡）"
    echo "  -o, --output <文件>   输出文件（默认: network_performance_report_时间戳.txt）"
    echo "  --no-iftop           禁用iftop流量监控（默认启用）"
    echo "  --no-tcp             禁用TCP参数监控（默认启用）"
    echo "  -h, --help           显示此帮助信息"
    exit 0
}

# 解析命令行参数
while [[ $# -gt 0 ]]; do
    case $1 in
        -i|--interval)
            INTERVAL="$2"
            shift 2
            ;;
        -d|--duration)
            DURATION="$2"
            shift 2
            ;;
        -e|--interface)
            INTERFACE="$2"
            shift 2
            ;;
        -o|--output)
            OUTPUT_FILE="$2"
            shift 2
            ;;
        --no-iftop)
            COLLECT_IFTOP=false
            shift
            ;;
        --no-tcp)
            COLLECT_TCP=false
            shift
            ;;
        -h|--help)
            show_help
            ;;
        *)
            echo "未知选项: $1"
            show_help
            ;;
    esac
done

# 检查必要的命令
check_commands() {
    local missing_commands=()
    
    for cmd in ifconfig ip ethtool sar netstat sysctl; do
        if ! command -v $cmd &> /dev/null; then
            missing_commands+=($cmd)
        fi
    done
    
    # 检查额外的工具
    if [ "$COLLECT_IFTOP" = true ] && ! command -v iftop &> /dev/null; then
        missing_commands+=(iftop)
    fi
    
    if [ ${#missing_commands[@]} -ne 0 ]; then
        echo -e "${RED}错误: 以下命令不可用: ${missing_commands[*]}${NC}"
        echo "请安装必要的工具包:"
        echo "  - ifconfig: net-tools 包"
        echo "  - ip: iproute2 包"
        echo "  - ethtool: ethtool 包"
        echo "  - sar: sysstat 包"
        echo "  - netstat: net-tools 包"
        echo "  - sysctl: procps 包"
        if [ "$COLLECT_IFTOP" = true ]; then
            echo "  - iftop: iftop 包"
        fi
        exit 1
    fi
}

# 获取默认网卡
get_default_interface() {
    local default_iface=""
    
    # 尝试方法1：通过默认路由获取
    if command -v ip &> /dev/null; then
        default_iface=$(ip route | grep default | awk '{print $5}' | head -n 1)
    fi
    
    # 尝试方法2：如果方法1失败，通过ifconfig查找活跃网卡
    if [ -z "$default_iface" ] && command -v ifconfig &> /dev/null; then
        default_iface=$(ifconfig | grep -E "^[a-zA-Z0-9]+" | grep -v "lo" | head -n 1 | cut -d ":" -f 1)
    fi
    
    # 如果还是失败，使用回退值
    if [ -z "$default_iface" ]; then
        echo -e "${YELLOW}警告: 无法自动检测默认网卡，使用eth0${NC}"
        default_iface="eth0"
    fi
    
    echo "$default_iface"
}

# 如果未指定网卡，则获取默认网卡
if [ -z "$INTERFACE" ]; then
    INTERFACE=$(get_default_interface)
fi

echo -e "${BLUE}使用网卡: $INTERFACE${NC}"

# 创建输出文件
echo "=== Linux 网络性能监控报告 ===" > "$OUTPUT_FILE"
echo "开始时间: $(date)" >> "$OUTPUT_FILE"
echo "采样间隔: ${INTERVAL}秒" >> "$OUTPUT_FILE"
echo "监控时长: ${DURATION}秒" >> "$OUTPUT_FILE"
echo "监控网卡: ${INTERFACE}" >> "$OUTPUT_FILE"
echo "----------------------------------------" >> "$OUTPUT_FILE"

# 检查命令
check_commands

# 初始化计数器
count=0
total_samples=$((DURATION / INTERVAL))

# 创建临时文件存储数据
temp_bandwidth="/tmp/bandwidth_$$.tmp"
temp_throughput="/tmp/throughput_$$.tmp"
temp_hw_errors="/tmp/hw_errors_$$.tmp"
temp_if_errors="/tmp/if_errors_$$.tmp"
temp_pps="/tmp/pps_$$.tmp"
temp_iftop="/tmp/iftop_$$.tmp"
temp_tcp_params="/tmp/tcp_params_$$.tmp"
temp_tcp_stats="/tmp/tcp_stats_$$.tmp"

# 创建临时文件
touch "$temp_bandwidth" "$temp_throughput" "$temp_hw_errors" "$temp_if_errors" "$temp_pps"
if [ "$COLLECT_IFTOP" = true ]; then
    touch "$temp_iftop"
fi
if [ "$COLLECT_TCP" = true ]; then
    touch "$temp_tcp_params" "$temp_tcp_stats"
fi

# 清理函数
cleanup() {
    # 检查是否已经清理过
    if [ -n "$CLEANUP_DONE" ]; then
        return
    fi
    
    rm -f "$temp_bandwidth" "$temp_throughput" "$temp_hw_errors" "$temp_if_errors" "$temp_pps" "$temp_iftop" "$temp_tcp_params" "$temp_tcp_stats"
    
    # 杀掉可能仍在运行的后台进程
    if [ -n "$iftop_pid" ] && ps -p $iftop_pid > /dev/null; then
        kill $iftop_pid 2>/dev/null
    fi
    
    echo -e "\n${GREEN}监控已完成，报告已保存到: $OUTPUT_FILE${NC}"
    
    # 标记清理已完成
    CLEANUP_DONE=1
    
    # 只有在非正常退出时才退出
    if [ -n "$1" ]; then
        exit 1
    fi
}

# 收集TCP内核参数
collect_tcp_params() {
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    local params=""
    
    # 1. 连接管理参数
    params+=" tcp_max_syn_backlog=$(sysctl -n net.ipv4.tcp_max_syn_backlog 2>/dev/null || echo NA)"
    params+=" tcp_syn_retries=$(sysctl -n net.ipv4.tcp_syn_retries 2>/dev/null || echo NA)"
    params+=" tcp_synack_retries=$(sysctl -n net.ipv4.tcp_synack_retries 2>/dev/null || echo NA)"
    params+=" tcp_tw_reuse=$(sysctl -n net.ipv4.tcp_tw_reuse 2>/dev/null || echo NA)"
    
    # 2. 拥塞控制参数
    params+=" tcp_congestion_control=$(sysctl -n net.ipv4.tcp_congestion_control 2>/dev/null || echo NA)"
    params+=" tcp_sack=$(sysctl -n net.ipv4.tcp_sack 2>/dev/null || echo NA)"
    
    # 3. 传输效率参数
    params+=" tcp_window_scaling=$(sysctl -n net.ipv4.tcp_window_scaling 2>/dev/null || echo NA)"
    tcp_rmem=$(sysctl -n net.ipv4.tcp_rmem 2>/dev/null || echo "NA NA NA")
    tcp_wmem=$(sysctl -n net.ipv4.tcp_wmem 2>/dev/null || echo "NA NA NA")
    params+=" tcp_rmem=\"$tcp_rmem\""
    params+=" tcp_wmem=\"$tcp_wmem\""
    
    # 4. 安全与稳定性参数
    params+=" tcp_syncookies=$(sysctl -n net.ipv4.tcp_syncookies 2>/dev/null || echo NA)"
    params+=" tcp_keepalive_time=$(sysctl -n net.ipv4.tcp_keepalive_time 2>/dev/null || echo NA)"
    
    # 5. 其他关键参数
    params+=" somaxconn=$(sysctl -n net.core.somaxconn 2>/dev/null || echo NA)"
    local_port_range=$(sysctl -n net.ipv4.ip_local_port_range 2>/dev/null || echo "NA NA")
    params+=" ip_local_port_range=\"$local_port_range\""
    
    echo "$timestamp TCP_PARAMS$params" >> "$temp_tcp_params"
}

# 收集TCP统计数据
collect_tcp_stats() {
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    
    # 获取ss -ti输出
    ss_output=$(ss -ti 2>/dev/null)
    
    # 分析ss输出以获取关键TCP指标
    # 提取拥塞控制算法
    local cong_ctrl=$(echo "$ss_output" | grep -oP "congestion_algorithm:\K[^ ,]+" | sort | uniq -c | awk '{print $2"("$1")"}' | paste -sd "," -)
    [ -z "$cong_ctrl" ] && cong_ctrl="NA"
    
    # 提取RTT和RTO信息
    local rtt_stats=$(echo "$ss_output" | grep -oP "rtt:\K[^ ]+" | tr -d ',')
    local rtt_avg=0
    local rtt_count=0
    local rtt_min=0
    local rtt_max=0
    
    for rtt in $rtt_stats; do
        # 提取RTT值，并移除小数部分，转换为整数
        rtt_int=$(echo "$rtt" | awk -F'/' '{print int($1)}')
        if [ $rtt_count -eq 0 ]; then
            rtt_min=$rtt_int
            rtt_max=$rtt_int
        fi
        
        # 使用bc进行浮点数比较
        if (( $(echo "$rtt_int < $rtt_min" | bc -l) )); then
            rtt_min=$rtt_int
        fi
        if (( $(echo "$rtt_int > $rtt_max" | bc -l) )); then
            rtt_max=$rtt_int
        fi
        
        rtt_avg=$(echo "$rtt_avg + $rtt_int" | bc -l)
        rtt_count=$((rtt_count + 1))
    done
    
    if [ $rtt_count -gt 0 ]; then
        rtt_avg=$(echo "scale=0; $rtt_avg / $rtt_count" | bc -l)
    else
        rtt_min="NA"
        rtt_max="NA"
        rtt_avg="NA"
    fi
    
    # 提取RTO
    local rto_stats=$(echo "$ss_output" | grep -oP "rto:\K[0-9.]+" | tr -d ',')
    local rto_avg=0
    local rto_count=0
    
    for rto in $rto_stats; do
        rto_avg=$(echo "scale=2; $rto_avg + $rto" | bc -l)
        rto_count=$((rto_count + 1))
    done
    
    if [ $rto_count -gt 0 ]; then
        rto_avg=$(echo "scale=2; $rto_avg / $rto_count" | bc -l)
    else
        rto_avg="NA"
    fi
    
    # 提取窗口大小
    local rcv_space=$(echo "$ss_output" | grep -oP "rcv_space:\K[0-9]+" | tr -d ',')
    local rcv_space_avg=0
    local rcv_space_count=0
    
    for space in $rcv_space; do
        rcv_space_avg=$((rcv_space_avg + space))
        rcv_space_count=$((rcv_space_count + 1))
    done
    
    if [ $rcv_space_count -gt 0 ]; then
        rcv_space_avg=$((rcv_space_avg / rcv_space_count))
    else
        rcv_space_avg="NA"
    fi
    
    # 提取MSS/PMTU
    local mss_stats=$(echo "$ss_output" | grep -oP "mss:\K[0-9]+" | tr -d ',')
    local mss_avg=0
    local mss_count=0
    
    for mss in $mss_stats; do
        mss_avg=$((mss_avg + mss))
        mss_count=$((mss_count + 1))
    done
    
    if [ $mss_count -gt 0 ]; then
        mss_avg=$((mss_avg / mss_count))
    else
        mss_avg="NA"
    fi
    
    # 提取流量控制速率 (pacing_rate/delivery_rate)
    local pacing_rate=$(echo "$ss_output" | grep -oP "pacing_rate \K[^/]+" | head -1 | tr -d ' ' || echo "NA")
    local delivery_rate=$(echo "$ss_output" | grep -oP "delivery_rate \K[^/]+" | head -1 | tr -d ' ' || echo "NA")
    
    # 提取重传次数
    local retrans_count=$(echo "$ss_output" | grep -c "retrans")
    if [ "$retrans_count" -eq 0 ]; then
        retrans="0"
    else
        retrans=$(echo "$ss_output" | grep -oP "retrans:\K[0-9]+" | tr -d ',' | paste -sd "+" - | bc -l)
        [ -z "$retrans" ] && retrans="0"
    fi
    
    # 零窗口事件
    local zero_window=$(echo "$ss_output" | grep -c "zero win")
    
    # 将数据写入临时文件
    echo "$timestamp TCP_STATS cong_ctrl=$cong_ctrl rtt_min=$rtt_min rtt_avg=$rtt_avg rtt_max=$rtt_max rto_avg=$rto_avg rcv_space=$rcv_space_avg mss=$mss_avg pacing_rate=$pacing_rate delivery_rate=$delivery_rate retrans=$retrans zero_window=$zero_window" >> "$temp_tcp_stats"
}

# 设置清理陷阱
trap 'cleanup 1' EXIT INT TERM

# 启动iftop后台监控（如果启用）
iftop_pid=""
if [ "$COLLECT_IFTOP" = true ]; then
    (
        # 使用iftop的-s参数指定运行时长
        timestamp=$(date '+%Y-%m-%d %H:%M:%S')
        echo "$timestamp IFTOP_START" >> "$temp_iftop"
        
        # 运行iftop并捕获输出
        iftop -i $INTERFACE -t -s $DURATION -n 2>/dev/null | while read -r line; do
            if [[ -n "$line" && "$line" != *"interface"* ]]; then
                echo "$line" >> "$temp_iftop"
            fi
        done
        
        timestamp=$(date '+%Y-%m-%d %H:%M:%S')
        echo "$timestamp IFTOP_END" >> "$temp_iftop"
    ) &
    iftop_pid=$!
fi

# 如果启用TCP监控，先收集静态TCP参数
if [ "$COLLECT_TCP" = true ]; then
    collect_tcp_params
fi

# 绘制进度条函数
draw_progress_bar() {
    local percent=$1
    local width=50
    local completed=$((width * percent / 100))
    local remaining=$((width - completed))
    local bar=$(printf "%${completed}s" | tr " " "#")
    local space=$(printf "%${remaining}s")
    printf "\r${YELLOW}[${bar}${space}] %3d%%${NC}" $percent
}

# 获取网卡理论带宽
get_interface_speed() {
    local interface=$1
    local speed=0
    
    if ethtool $interface &> /dev/null; then
        speed=$(ethtool $interface 2>/dev/null | grep "Speed:" | awk '{print $2}' | tr -d 'Mb/s')
        if [ -z "$speed" ]; then
            speed=0
        fi
    fi
    
    echo "$speed"
}

echo -e "${BLUE}开始监控网络性能...${NC}"
echo -e "采样间隔: ${INTERVAL}秒"
echo -e "监控时长: ${DURATION}秒"
echo -e "监控网卡: ${INTERFACE}"
echo -e "输出文件: $OUTPUT_FILE"
echo -e "按 Ctrl+C 可以提前结束监控\n"

# 记录网卡理论带宽
speed=$(get_interface_speed "$INTERFACE")
echo "$(date '+%Y-%m-%d %H:%M:%S') BANDWIDTH $INTERFACE $speed" >> "$temp_bandwidth"

# 主循环
while [ $count -lt $total_samples ]; do
    timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    
    # 收集网卡吞吐量数据
    rx_bytes_before=$(cat /sys/class/net/$INTERFACE/statistics/rx_bytes 2>/dev/null || echo 0)
    tx_bytes_before=$(cat /sys/class/net/$INTERFACE/statistics/tx_bytes 2>/dev/null || echo 0)
    sleep 1  # 采样1秒
    rx_bytes_after=$(cat /sys/class/net/$INTERFACE/statistics/rx_bytes 2>/dev/null || echo 0)
    tx_bytes_after=$(cat /sys/class/net/$INTERFACE/statistics/tx_bytes 2>/dev/null || echo 0)
    
    rx_bytes_delta=$((rx_bytes_after - rx_bytes_before))
    tx_bytes_delta=$((tx_bytes_after - tx_bytes_before))
    
    # 转换为KB/s和MB/s
    rx_kbps=$(echo "scale=2; $rx_bytes_delta / 1024" | bc)
    tx_kbps=$(echo "scale=2; $tx_bytes_delta / 1024" | bc)
    rx_mbps=$(echo "scale=2; $rx_bytes_delta / 1048576" | bc)
    tx_mbps=$(echo "scale=2; $tx_bytes_delta / 1048576" | bc)
    
    echo "$timestamp THROUGHPUT $INTERFACE $rx_bytes_delta $tx_bytes_delta $rx_kbps $tx_kbps $rx_mbps $tx_mbps" >> "$temp_throughput"
    
    # 收集网卡硬件错误统计 - 采集关键错误指标
    # 从ethtool -S输出中提取重要的错误计数
    rx_errors_hw=$(ethtool -S $INTERFACE 2>/dev/null | grep -E "rx_errors" | head -n 1 | awk '{print $2}' || echo 0)
    tx_errors_hw=$(ethtool -S $INTERFACE 2>/dev/null | grep -E "tx_errors" | head -n 1 | awk '{print $2}' || echo 0)
    rx_dropped_hw=$(ethtool -S $INTERFACE 2>/dev/null | grep -E "rx_dropped" | head -n 1 | awk '{print $2}' || echo 0)
    tx_dropped_hw=$(ethtool -S $INTERFACE 2>/dev/null | grep -E "tx_dropped" | head -n 1 | awk '{print $2}' || echo 0)
    rx_crc_errors=$(ethtool -S $INTERFACE 2>/dev/null | grep -E "rx_crc_errors|crc_errors" | head -n 1 | awk '{print $2}' || echo 0)
    rx_frame_errors_hw=$(ethtool -S $INTERFACE 2>/dev/null | grep -E "rx_frame_errors|frame_errors" | head -n 1 | awk '{print $2}' || echo 0)
    rx_fifo_errors=$(ethtool -S $INTERFACE 2>/dev/null | grep -E "rx_fifo_errors|fifo_errors" | head -n 1 | awk '{print $2}' || echo 0)
    tx_fifo_errors=$(ethtool -S $INTERFACE 2>/dev/null | grep -E "tx_fifo_errors" | head -n 1 | awk '{print $2}' || echo 0)
    collisions_hw=$(ethtool -S $INTERFACE 2>/dev/null | grep -E "^[[:space:]]*collisions" | head -n 1 | awk '{print $2}' || echo 0)

    # 保存数据到临时文件
    echo "$timestamp HW_ERROR $INTERFACE rx_errors $rx_errors_hw tx_errors $tx_errors_hw rx_dropped $rx_dropped_hw tx_dropped $tx_dropped_hw rx_crc_errors $rx_crc_errors rx_frame_errors $rx_frame_errors_hw rx_fifo_errors $rx_fifo_errors tx_fifo_errors $tx_fifo_errors collisions $collisions_hw" >> "$temp_hw_errors"
    
    # 收集网卡PPS（每秒包数）
    rx_packets_before=$(cat /sys/class/net/$INTERFACE/statistics/rx_packets 2>/dev/null || echo 0)
    tx_packets_before=$(cat /sys/class/net/$INTERFACE/statistics/tx_packets 2>/dev/null || echo 0)
    sleep 1  # 采样1秒
    rx_packets_after=$(cat /sys/class/net/$INTERFACE/statistics/rx_packets 2>/dev/null || echo 0)
    tx_packets_after=$(cat /sys/class/net/$INTERFACE/statistics/tx_packets 2>/dev/null || echo 0)
    
    rx_pps=$((rx_packets_after - rx_packets_before))
    tx_pps=$((tx_packets_after - tx_packets_before))
    total_pps=$((rx_pps + tx_pps))
    
    echo "$timestamp PPS $INTERFACE $rx_pps $tx_pps $total_pps" >> "$temp_pps"
    
    # 如果启用TCP监控，收集TCP统计数据
    if [ "$COLLECT_TCP" = true ] && [ $((count % 5)) -eq 0 ]; then
        # 每隔5个采样周期收集一次TCP统计数据
        collect_tcp_stats
    fi
    
    # 显示进度条
    progress=$((100 * count / total_samples))
    draw_progress_bar $progress
    
    # 等待指定的间隔时间
    sleep $INTERVAL
    
    count=$((count + 1))
done

# 完成时显示100%的进度条
draw_progress_bar 100
echo -e "\n\n${GREEN}正在生成报告...${NC}"

# 生成统计报告
echo -e "\n=== 网卡理论带宽上限 ===" >> "$OUTPUT_FILE"
echo "时间戳                网卡    理论带宽(Mbps)" >> "$OUTPUT_FILE"
echo "------------------------------------------------" >> "$OUTPUT_FILE"
while read -r line; do
    if [[ "$line" == *"BANDWIDTH"* ]]; then
        timestamp=$(echo "$line" | cut -d' ' -f1,2)
        interface=$(echo "$line" | cut -d' ' -f4)
        speed=$(echo "$line" | cut -d' ' -f5)
        
        awk -v ts="$timestamp" -v iface="$interface" -v spd="$speed" \
            'BEGIN {printf "%-20s %-8s %10d\n", ts, iface, spd}' >> "$OUTPUT_FILE"
    fi
done < "$temp_bandwidth"

echo -e "\n=== 网络吞吐量统计 ===" >> "$OUTPUT_FILE"
echo "时间戳                网卡    接收(B/s)    发送(B/s)    接收(KB/s)   发送(KB/s)   接收(MB/s)   发送(MB/s)" >> "$OUTPUT_FILE"
echo "------------------------------------------------" >> "$OUTPUT_FILE"
current_timestamp=""
while read -r line; do
    if [[ "$line" == *"THROUGHPUT"* ]]; then
        timestamp=$(echo "$line" | cut -d' ' -f1,2)
        interface=$(echo "$line" | cut -d' ' -f4)
        rx_bytes=$(echo "$line" | cut -d' ' -f5)
        tx_bytes=$(echo "$line" | cut -d' ' -f6)
        rx_kbps=$(echo "$line" | cut -d' ' -f7)
        tx_kbps=$(echo "$line" | cut -d' ' -f8)
        rx_mbps=$(echo "$line" | cut -d' ' -f9)
        tx_mbps=$(echo "$line" | cut -d' ' -f10)
        
        # 如果时间戳变化，添加一个空行
        if [[ -n "$current_timestamp" && "$current_timestamp" != "$timestamp" ]]; then
            echo "" >> "$OUTPUT_FILE"
        fi
        
        awk -v ts="$timestamp" -v iface="$interface" -v rxb="$rx_bytes" -v txb="$tx_bytes" -v rxk="$rx_kbps" -v txk="$tx_kbps" -v rxm="$rx_mbps" -v txm="$tx_mbps" \
            'BEGIN {printf "%-20s %-8s %12d %12d %12.2f %12.2f %12.2f %12.2f\n", ts, iface, rxb, txb, rxk, txk, rxm, txm}' >> "$OUTPUT_FILE"
        
        current_timestamp="$timestamp"
    fi
done < "$temp_throughput"

echo -e "\n=== 网络接口错误统计 ===" >> "$OUTPUT_FILE"
echo "时间戳                网卡    接收错误    发送错误    接收丢包    发送丢包    CRC错误     帧错误      接收FIFO错误 发送FIFO错误 冲突" >> "$OUTPUT_FILE"
echo "------------------------------------------------" >> "$OUTPUT_FILE"
current_timestamp=""
while read -r line; do
    if [[ "$line" == *"HW_ERROR"* ]]; then
        timestamp=$(echo "$line" | cut -d' ' -f1,2)
        interface=$(echo "$line" | cut -d' ' -f4)
        
        # 提取各种错误计数
        rx_errors_hw=$(echo "$line" | grep -oP "rx_errors \K[0-9]+" || echo 0)
        tx_errors_hw=$(echo "$line" | grep -oP "tx_errors \K[0-9]+" || echo 0)
        rx_dropped_hw=$(echo "$line" | grep -oP "rx_dropped \K[0-9]+" || echo 0)
        tx_dropped_hw=$(echo "$line" | grep -oP "tx_dropped \K[0-9]+" || echo 0)
        rx_crc_errors=$(echo "$line" | grep -oP "rx_crc_errors \K[0-9]+" || echo 0)
        rx_frame_errors_hw=$(echo "$line" | grep -oP "rx_frame_errors \K[0-9]+" || echo 0)
        rx_fifo_errors=$(echo "$line" | grep -oP "rx_fifo_errors \K[0-9]+" || echo 0)
        tx_fifo_errors=$(echo "$line" | grep -oP "tx_fifo_errors \K[0-9]+" || echo 0)
        collisions_hw=$(echo "$line" | grep -oP "collisions \K[0-9]+" || echo 0)
        
        # 如果时间戳变化，添加一个空行
        if [[ -n "$current_timestamp" && "$current_timestamp" != "$timestamp" ]]; then
            echo "" >> "$OUTPUT_FILE"
        fi
        
        awk -v ts="$timestamp" -v iface="$interface" \
            -v rxe="$rx_errors_hw" -v txe="$tx_errors_hw" \
            -v rxd="$rx_dropped_hw" -v txd="$tx_dropped_hw" \
            -v crc="$rx_crc_errors" -v frm="$rx_frame_errors_hw" \
            -v rxf="$rx_fifo_errors" -v txf="$tx_fifo_errors" \
            -v col="$collisions_hw" \
            'BEGIN {printf "%-20s %-8s %10d %10d %10d %10d %10d %10d %10d %10d %10d\n", 
                ts, iface, rxe, txe, rxd, txd, crc, frm, rxf, txf, col}' >> "$OUTPUT_FILE"
        
        current_timestamp="$timestamp"
    fi
done < "$temp_hw_errors"

echo -e "\n=== 网卡PPS统计 ===" >> "$OUTPUT_FILE"
echo "时间戳                网卡    接收PPS     发送PPS     总PPS" >> "$OUTPUT_FILE"
echo "------------------------------------------------" >> "$OUTPUT_FILE"
current_timestamp=""
while read -r line; do
    if [[ "$line" == *"PPS"* ]]; then
        timestamp=$(echo "$line" | cut -d' ' -f1,2)
        interface=$(echo "$line" | cut -d' ' -f4)
        rx_pps=$(echo "$line" | cut -d' ' -f5)
        tx_pps=$(echo "$line" | cut -d' ' -f6)
        total_pps=$(echo "$line" | cut -d' ' -f7)
        
        # 如果时间戳变化，添加一个空行
        if [[ -n "$current_timestamp" && "$current_timestamp" != "$timestamp" ]]; then
            echo "" >> "$OUTPUT_FILE"
        fi
        
        awk -v ts="$timestamp" -v iface="$interface" -v rxp="$rx_pps" -v txp="$tx_pps" -v tp="$total_pps" \
            'BEGIN {printf "%-20s %-8s %10d %10d %10d\n", ts, iface, rxp, txp, tp}' >> "$OUTPUT_FILE"
        
        current_timestamp="$timestamp"
    fi
done < "$temp_pps"

# 收集TCP参数
if [ "$COLLECT_TCP" = true ]; then
    echo -e "\n=== TCP内核参数 ===" >> "$OUTPUT_FILE"
    echo "----------------------------------------" >> "$OUTPUT_FILE"
    
    # 提取并显示TCP参数
    if [ -s "$temp_tcp_params" ]; then
        # 提取第一行，包含最重要的TCP参数
        tcp_params_line=$(head -n 1 "$temp_tcp_params")
        
        # 解析参数
        somaxconn=$(echo "$tcp_params_line" | grep -oP 'net.core.somaxconn="\K[^"]+')
        local_port_range=$(echo "$tcp_params_line" | grep -oP 'ip_local_port_range="\K[^"]+')
        
        echo "  net.core.somaxconn = $somaxconn" >> "$OUTPUT_FILE"
        echo "  net.ipv4.ip_local_port_range = $local_port_range" >> "$OUTPUT_FILE"
    else
        echo "未收集到TCP参数数据" >> "$OUTPUT_FILE"
    fi
fi

# 生成iftop连接详情报告（如果启用）
if [ "$COLLECT_IFTOP" = true ]; then
    echo -e "\n=== 网络连接详情 (iftop) ===" >> "$OUTPUT_FILE"
    echo "iftop监控时间段: ${DURATION}秒" >> "$OUTPUT_FILE"
    echo "------------------------------------------------" >> "$OUTPUT_FILE"
    
    # 检查iftop数据是否存在
    if [ -s "$temp_iftop" ]; then
        start_timestamp=$(grep "IFTOP_START" "$temp_iftop" | head -n 1 | cut -d' ' -f1,2)
        end_timestamp=$(grep "IFTOP_END" "$temp_iftop" | tail -n 1 | cut -d' ' -f1,2)
        
        echo "开始时间: $start_timestamp" >> "$OUTPUT_FILE"
        echo "结束时间: $end_timestamp" >> "$OUTPUT_FILE"
        echo "" >> "$OUTPUT_FILE"
        
        echo "连接详情:" >> "$OUTPUT_FILE"
        echo "------------------------------------------------" >> "$OUTPUT_FILE"
        
        # 提取iftop数据（不包括标记行）
        sed -n '/IFTOP_START/,/IFTOP_END/p' "$temp_iftop" | grep -v "IFTOP_" >> "$OUTPUT_FILE"
    else
        echo "未收集到iftop数据" >> "$OUTPUT_FILE"
    fi
fi

# 计算平均值
echo -e "\n=== 统计摘要 ===" >> "$OUTPUT_FILE"
echo "------------------------------------------------" >> "$OUTPUT_FILE"

# 理论带宽
speed=$(cat "$temp_bandwidth" | grep BANDWIDTH | head -n 1 | cut -d' ' -f5)
echo "网卡 $INTERFACE 理论带宽: ${speed} Mbps" >> "$OUTPUT_FILE"

# 平均吞吐量
rx_bytes_avg=$(awk -v iface="$INTERFACE" '/THROUGHPUT/ && $4==iface {sum+=$5; count++} END {print (count>0) ? sum/count : 0}' "$temp_throughput")
tx_bytes_avg=$(awk -v iface="$INTERFACE" '/THROUGHPUT/ && $4==iface {sum+=$6; count++} END {print (count>0) ? sum/count : 0}' "$temp_throughput")
rx_kbps_avg=$(awk -v iface="$INTERFACE" '/THROUGHPUT/ && $4==iface {sum+=$7; count++} END {print (count>0) ? sum/count : 0}' "$temp_throughput")
tx_kbps_avg=$(awk -v iface="$INTERFACE" '/THROUGHPUT/ && $4==iface {sum+=$8; count++} END {print (count>0) ? sum/count : 0}' "$temp_throughput")
rx_mbps_avg=$(awk -v iface="$INTERFACE" '/THROUGHPUT/ && $4==iface {sum+=$9; count++} END {print (count>0) ? sum/count : 0}' "$temp_throughput")
tx_mbps_avg=$(awk -v iface="$INTERFACE" '/THROUGHPUT/ && $4==iface {sum+=$10; count++} END {print (count>0) ? sum/count : 0}' "$temp_throughput")

echo "网卡 $INTERFACE 平均吞吐量:" >> "$OUTPUT_FILE"
echo "  接收: ${rx_bytes_avg} B/s (${rx_kbps_avg} KB/s, ${rx_mbps_avg} MB/s)" >> "$OUTPUT_FILE"
echo "  发送: ${tx_bytes_avg} B/s (${tx_kbps_avg} KB/s, ${tx_mbps_avg} MB/s)" >> "$OUTPUT_FILE"

# 带宽利用率
if [ "$speed" -gt 0 ]; then
    rx_util=$(echo "scale=2; ($rx_mbps_avg * 8 * 100) / $speed" | bc)
    tx_util=$(echo "scale=2; ($tx_mbps_avg * 8 * 100) / $speed" | bc)
    echo "  带宽利用率: 接收=${rx_util}%, 发送=${tx_util}%" >> "$OUTPUT_FILE"
fi

# 网络错误统计
echo "网卡 $INTERFACE 网络错误统计:" >> "$OUTPUT_FILE"

# 提取最后一次硬件错误统计的数据
last_hw_error=$(tail -n 1 "$temp_hw_errors")
rx_errors_hw=$(echo "$last_hw_error" | grep -oP "rx_errors \K[0-9]+" || echo 0)
tx_errors_hw=$(echo "$last_hw_error" | grep -oP "tx_errors \K[0-9]+" || echo 0)
rx_dropped_hw=$(echo "$last_hw_error" | grep -oP "rx_dropped \K[0-9]+" || echo 0)
tx_dropped_hw=$(echo "$last_hw_error" | grep -oP "tx_dropped \K[0-9]+" || echo 0)
rx_crc_errors=$(echo "$last_hw_error" | grep -oP "rx_crc_errors \K[0-9]+" || echo 0)
rx_frame_errors_hw=$(echo "$last_hw_error" | grep -oP "rx_frame_errors \K[0-9]+" || echo 0)
rx_fifo_errors=$(echo "$last_hw_error" | grep -oP "rx_fifo_errors \K[0-9]+" || echo 0)
tx_fifo_errors=$(echo "$last_hw_error" | grep -oP "tx_fifo_errors \K[0-9]+" || echo 0)
collisions_hw=$(echo "$last_hw_error" | grep -oP "collisions \K[0-9]+" || echo 0)

echo "  接收错误: ${rx_errors_hw}" >> "$OUTPUT_FILE"
echo "  发送错误: ${tx_errors_hw}" >> "$OUTPUT_FILE"
echo "  接收丢包: ${rx_dropped_hw}" >> "$OUTPUT_FILE"
echo "  发送丢包: ${tx_dropped_hw}" >> "$OUTPUT_FILE"
echo "  CRC错误: ${rx_crc_errors}" >> "$OUTPUT_FILE"
echo "  帧错误: ${rx_frame_errors_hw}" >> "$OUTPUT_FILE"
echo "  接收FIFO错误: ${rx_fifo_errors}" >> "$OUTPUT_FILE"
echo "  发送FIFO错误: ${tx_fifo_errors}" >> "$OUTPUT_FILE"
echo "  冲突计数: ${collisions_hw}" >> "$OUTPUT_FILE"

# PPS统计
rx_pps_avg=$(awk -v iface="$INTERFACE" '/PPS/ && $4==iface {sum+=$5; count++} END {print (count>0) ? sum/count : 0}' "$temp_pps")
tx_pps_avg=$(awk -v iface="$INTERFACE" '/PPS/ && $4==iface {sum+=$6; count++} END {print (count>0) ? sum/count : 0}' "$temp_pps")
total_pps_avg=$(awk -v iface="$INTERFACE" '/PPS/ && $4==iface {sum+=$7; count++} END {print (count>0) ? sum/count : 0}' "$temp_pps")

echo "" >> "$OUTPUT_FILE"
echo "网卡 $INTERFACE 平均PPS:" >> "$OUTPUT_FILE"
echo "  接收PPS: ${rx_pps_avg} 包/秒" >> "$OUTPUT_FILE"
echo "  发送PPS: ${tx_pps_avg} 包/秒" >> "$OUTPUT_FILE"
echo "  总PPS: ${total_pps_avg} 包/秒" >> "$OUTPUT_FILE"

echo -e "\n结束时间: $(date)" >> "$OUTPUT_FILE"
echo "----------------------------------------" >> "$OUTPUT_FILE"

# 正常完成，调用cleanup但不退出
cleanup
